package com.credit.jumu.playcard.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.credit.jumu.playcard.BuildConfig;
import com.credit.jumu.playcard.R;
import com.credit.jumu.playcard.activity.BindingCardActivity;
import com.credit.jumu.playcard.activity.MyWebActivity;
import com.credit.jumu.playcard.activity.ProductDetailActivity;
import com.credit.jumu.playcard.adapter.HomeProListAdapter;
import com.credit.jumu.playcard.base.BaseFragment;
import com.credit.jumu.playcard.bean.BannerInfo;
import com.credit.jumu.playcard.bean.HomeListInfo;
import com.credit.jumu.playcard.cardapp.CardApp;
import com.credit.jumu.playcard.utils.DataSharedPreference;
import com.credit.jumu.playcard.utils.GlideUtil;
import com.credit.jumu.playcard.utils.JsonUtils;
import com.credit.jumu.playcard.utils.LogUtils;
import com.credit.jumu.playcard.utils.MD5Encoder;
import com.credit.jumu.playcard.utils.MyStylesToast;
import com.credit.jumu.playcard.utils.SignUtil;
import com.credit.jumu.playcard.utils.SystemUtil;
import com.credit.jumu.playcard.utils.ToastUtil;
import com.credit.jumu.playcard.utils.TypeUtils;
import com.credit.jumu.playcard.utils.UrlsUtils;
import com.credit.jumu.playcard.view.MySwipeRefreshLayout;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import net.sf.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;


/**
 * Created by jpeng on 16-11-14.
 */
public class HomeTabFragment extends BaseFragment implements OnItemClickListener, SwipeRefreshLayout.OnRefreshListener, View.OnClickListener, HomeProListAdapter.GoMoneyOnClick {
	ListView homeList;
	private List<HomeListInfo> mlistInfo = new ArrayList<HomeListInfo>();
	public Context context;
	ConvenientBanner convenient;
	private DataSharedPreference ds;
	MySwipeRefreshLayout mSwipeRefreshLayout;
	LinearLayout homemore1, homemore2, homemore3, homemore4, homemore5, homemore6, homemore7, homemore8;
	HomeProListAdapter homeProListAdapter;
	Boolean isfirst = true;
	ArrayList<BannerInfo> localImages = new ArrayList<>();

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_hometab, container, false);
		homeList = view.findViewById(R.id.homeList);
		mSwipeRefreshLayout = view.findViewById(R.id.mSwipeRefreshLayout);
		mSwipeRefreshLayout.setOnRefreshListener(this);
		mSwipeRefreshLayout.setTouchSlop(300);
		return view;
	}

	@Override
	public void onResume() {
		if (isfirst) {
			initView();
		}
		isfirst = false;
		super.onResume();
	}

	public void initView() {
		context = getActivity();
		View view = LayoutInflater.from(context).inflate(R.layout.view_home_head, null);
		homemore1 = view.findViewById(R.id.homemore1);
		homemore2 = view.findViewById(R.id.homemore2);
		homemore3 = view.findViewById(R.id.homemore3);
		homemore4 = view.findViewById(R.id.homemore4);
		homemore5 = view.findViewById(R.id.homemore5);
		homemore6 = view.findViewById(R.id.homemore6);
		homemore7 = view.findViewById(R.id.homemore7);
		homemore8 = view.findViewById(R.id.homemore8);
		homemore1.setOnClickListener(this);
		homemore2.setOnClickListener(this);
		homemore3.setOnClickListener(this);
		homemore4.setOnClickListener(this);
		homemore5.setOnClickListener(this);
		homemore6.setOnClickListener(this);
		homemore7.setOnClickListener(this);
		homemore8.setOnClickListener(this);

		convenient = view.findViewById(R.id.myconvenient);
		homeList.addHeaderView(view);
		homeProListAdapter = new HomeProListAdapter(mlistInfo, context, this);
		homeList.setAdapter(homeProListAdapter);
		homeList.setOnScrollListener(new MyScrollListener());
		homeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (position >= 1) {
					initProductGo(mlistInfo.get(position - 1).getProid());
					//	getMessageCode.GetMessageCode(ds.getUUID(),"register","15691756125");
				}
			}
		});
		if (null == ds) {
			ds = new DataSharedPreference(getActivity());
		}
		ds.setUUID(SystemUtil.getAndroidId(getActivity()));
		initBannerData();
		initProductData();
	}

	private void initProducturlGo(String id) {

		LinkedHashMap<String, String> mapSign = new LinkedHashMap<>();
		if (TextUtils.isEmpty(ds.getAccountId()) || TextUtils.isEmpty(ds.getToken()))
			ToastUtil.showShortToast("请先登录");
		mapSign.put("accountId", ds.getAccountId());
		mapSign.put("deviceCode", ds.getUUID());
		mapSign.put("intefaceType", CardApp.intefaceType);
		mapSign.put("proId", id);
		mapSign.put("source", CardApp.source);
		mapSign.put("terminalId", "A");
		mapSign.put("timeStamp", SystemUtil.getSystemTime());
		mapSign.put("token", ds.getToken());
		mapSign.put("version", BuildConfig.VERSION_NAME);
		mapSign.put("key", CardApp.key);

		LinkedHashMap<String, String> mapPramas = new LinkedHashMap<>();
		mapPramas.put("accountId", ds.getAccountId());
		mapPramas.put("deviceCode", ds.getUUID());
		mapPramas.put("intefaceType", CardApp.intefaceType);
		mapPramas.put("proId", id);
		mapPramas.put("sign", MD5Encoder.encode(SignUtil.getSign(mapSign)));
		mapPramas.put("source", CardApp.source);
		mapPramas.put("terminalId", "A");
		mapPramas.put("timeStamp", SystemUtil.getSystemTime());
		mapPramas.put("token", ds.getToken());
		mapPramas.put("version", BuildConfig.VERSION_NAME);
		showLoading();
		OkGo.<String>post(UrlsUtils.HOME_PRODUCT_URL)
				.tag(this)
				.params(mapPramas)
				.execute(
						new StringCallback() {
							@Override
							public void onSuccess(Response<String> response) {
								dismissLoading();
								LogUtils.println("zhangyiyionSuccessURL_PRODUCT_TOGO------" + response.body());
								if (!TextUtils.isEmpty(response.body())) {
									JSONObject responseJson = JsonUtils.getJsonObject(response.body().toString());
									String code = TypeUtils.getJsonString(responseJson, "code", "");
									String message = TypeUtils.getJsonString(responseJson, "message", "");
									String goUrl = TypeUtils.getJsonString(responseJson, "goUrl", "");

									if (!"9999".equals(code)) {
										ToastUtil.showShortToast(message);
									} else {
										Intent intent = new Intent(getActivity(), MyWebActivity.class);
										intent.putExtra("url", goUrl);
										startActivity(intent);
									}
								}
							}

							@Override
							public void onError(Response<String> response) {
								dismissLoading();
								LogUtils.println("zhangyiyionErrorURL_PRODUCT_TOGO------" + response.body());
							}
						}
				);
	}

	private void initProductGo(String id) {
		if (TextUtils.isEmpty(ds.getAccountId()) || TextUtils.isEmpty(ds.getToken()))
			ToastUtil.showShortToast("请先登录");
		LinkedHashMap<String, String> mapSign = new LinkedHashMap<>();
		mapSign.put("accountId", ds.getAccountId());
		mapSign.put("deviceCode", ds.getUUID());
		mapSign.put("intefaceType", CardApp.intefaceType);
		mapSign.put("proId", id);
		mapSign.put("source", CardApp.source);
		mapSign.put("terminalId", "A");
		mapSign.put("timeStamp", SystemUtil.getSystemTime());
		mapSign.put("token", ds.getToken());
		mapSign.put("version", BuildConfig.VERSION_NAME);
		mapSign.put("key", CardApp.key);

		LinkedHashMap<String, String> mapPramas = new LinkedHashMap<>();
		mapPramas.put("accountId", ds.getAccountId());
		mapPramas.put("deviceCode", ds.getUUID());
		mapPramas.put("intefaceType", CardApp.intefaceType);
		mapPramas.put("proId", id);
		mapPramas.put("sign", MD5Encoder.encode(SignUtil.getSign(mapSign)));
		mapPramas.put("source", CardApp.source);
		mapPramas.put("terminalId", "A");
		mapPramas.put("timeStamp", SystemUtil.getSystemTime());
		mapPramas.put("token", ds.getToken());
		mapPramas.put("version", BuildConfig.VERSION_NAME);
		showLoading();
		OkGo.<String>post(UrlsUtils.HOME_PRODUCT_APPLY)
				.tag(this)
				.params(mapPramas)
				.execute(
						new StringCallback() {
							@Override
							public void onSuccess(Response<String> response) {
								dismissLoading();
								LogUtils.println("zhangyiyionSuccessURL_PRODUCT_TOGO------" + response.body());
								if (!TextUtils.isEmpty(response.body())) {
									JSONObject responseJson = JsonUtils.getJsonObject(response.body().toString());
									String code = TypeUtils.getJsonString(responseJson, "code", "");
									String message = TypeUtils.getJsonString(responseJson, "message", "");
									String goUrl = TypeUtils.getJsonString(responseJson, "goUrl", "");

									if (!"9999".equals(code)) {
										ToastUtil.showShortToast(message);
									} else {
										Intent intent = new Intent(getActivity(), ProductDetailActivity.class);
										intent.putExtra("responseData", response.body());
										startActivity(intent);
									}
								}
							}

							@Override
							public void onError(Response<String> response) {
								dismissLoading();
								LogUtils.println("zhangyiyionErrorURL_PRODUCT_TOGO------" + response.body());
							}
						}
				);
	}

	private void initProductData() {
		LinkedHashMap<String, String> mapSign = new LinkedHashMap<>();
		if (ds.getIsLog()) {
			mapSign.put("accountId", ds.getAccountId());
			mapSign.put("deviceCode", ds.getUUID());
			mapSign.put("intefaceType", CardApp.intefaceType);
			mapSign.put("page", "1");
			mapSign.put("pagesize", "20");
			mapSign.put("pushType", "1");
			mapSign.put("source", CardApp.source);
			mapSign.put("terminalId", "A");
			mapSign.put("timeStamp", SystemUtil.getSystemTime());
			mapSign.put("token", ds.getToken());
			mapSign.put("version", BuildConfig.VERSION_NAME);
			mapSign.put("key", CardApp.key);
		} else {
			mapSign.put("deviceCode", ds.getUUID());
			mapSign.put("intefaceType", CardApp.intefaceType);
			mapSign.put("page", "1");
			mapSign.put("pagesize", "20");
			mapSign.put("pushType", "1");
			mapSign.put("source", CardApp.source);
			mapSign.put("terminalId", "A");
			mapSign.put("timeStamp", SystemUtil.getSystemTime());
			mapSign.put("version", BuildConfig.VERSION_NAME);
			mapSign.put("key", CardApp.key);
		}


		LinkedHashMap<String, String> mapPramas = new LinkedHashMap<>();
		mapPramas.put("accountId", ds.getAccountId());
		mapPramas.put("cateId", "");
		mapPramas.put("deviceCode", ds.getUUID());
		mapPramas.put("intefaceType", CardApp.intefaceType);
		mapPramas.put("page", "1");
		mapPramas.put("pagesize", "20");
		mapPramas.put("pushType", "1");
		mapPramas.put("sign", MD5Encoder.encode(SignUtil.getSign(mapSign)));
		mapPramas.put("source", CardApp.source);
		mapPramas.put("terminalId", "A");
		mapPramas.put("timeStamp", SystemUtil.getSystemTime());
		mapPramas.put("token", ds.getToken());
		mapPramas.put("version", BuildConfig.VERSION_NAME);
		showLoading();
		OkGo.<String>post(UrlsUtils.URL_PRODUCT)//
				.tag(this)
				.params(mapPramas)
				.execute(
						new StringCallback() {
							@Override
							public void onSuccess(Response<String> response) {
								dismissLoading();
								LogUtils.println("zhangyiyionSuccessPRODUCT------" + response.body());
								if (!TextUtils.isEmpty(response.body())) {
									JSONObject responseJson = JsonUtils.getJsonObject(response.body().toString());
									JSONObject productList = TypeUtils.getJsonObject(TypeUtils.getJsonObject(responseJson, "productList"), "list");
									if (null == productList) return;
									Iterator<String> iterator = productList.keys();
									if (null == mlistInfo) {
										mlistInfo = new ArrayList<>();
									}
									while (iterator.hasNext()) {
										String key = iterator.next();
										JSONObject listInfo = TypeUtils.getJsonObject(productList, key);
										HomeListInfo proInfo = new HomeListInfo();
										proInfo.setProicon(TypeUtils.getJsonString(listInfo, "ProdLogo", ""));
										proInfo.setProtext(TypeUtils.getJsonString(listInfo, "ProdName", ""));
										proInfo.setMoneymax(TypeUtils.getJsonString(listInfo, "LoanMoneyB", ""));
										proInfo.setLongmaxtime(TypeUtils.getJsonString(listInfo, "LoanTermB", ""));
										proInfo.setInterest(TypeUtils.getJsonString(listInfo, "Rate", ""));
										proInfo.setProshow(TypeUtils.getJsonString(listInfo, "proddescription2", ""));//applyNum
										proInfo.setPeoplenum("有" + TypeUtils.getJsonString(listInfo, "applyNum", "") + "人申请");
										proInfo.setProid(TypeUtils.getJsonString(listInfo, "id", ""));
										mlistInfo.add(proInfo);
									}
									if (null != homeProListAdapter) {
										homeProListAdapter.notifyDataSetChanged();
									}
								}
							}

							@Override
							public void onError(Response<String> response) {
								dismissLoading();
								LogUtils.println("zhangyiyionErrorPRODUCT------" + response.body());
							}
						}
				);
	}

	private void initBannerData() {
		LinkedHashMap<String, String> mapSign = new LinkedHashMap<>();
		mapSign.put("deviceCode", ds.getUUID());
		mapSign.put("intefaceType", CardApp.intefaceType);
		mapSign.put("source", CardApp.source);
		mapSign.put("terminalId", "A");
		mapSign.put("timeStamp", SystemUtil.getSystemTime());
		mapSign.put("version", BuildConfig.VERSION_NAME);
		mapSign.put("key", CardApp.key);

		LinkedHashMap<String, String> mapPramas = new LinkedHashMap<>();
		mapPramas.put("accountId", "");
		mapPramas.put("deviceCode", ds.getUUID());
		mapPramas.put("intefaceType", CardApp.intefaceType);
		mapPramas.put("sign", MD5Encoder.encode(SignUtil.getSign(mapSign)));
		mapPramas.put("source", CardApp.source);
		mapPramas.put("terminalId", "A");
		mapPramas.put("timeStamp", SystemUtil.getSystemTime());
		mapPramas.put("token", "");
		mapPramas.put("version", BuildConfig.VERSION_NAME);
		OkGo.<String>post(UrlsUtils.HOME_BANNER)//
				.tag(this)
				.params(mapPramas)
				.execute(
						new StringCallback() {
							@Override
							public void onSuccess(Response<String> response) {
								JSONObject jsonObject = JsonUtils.getJsonObject(response.body().toString());
								JSONObject datas = TypeUtils.getJsonObject(jsonObject, "banner_data");
								if (null == datas) return;
								Iterator<String> iterator = datas.keys();
								while (iterator.hasNext()) {
									BannerInfo nanner = new BannerInfo();
									String key = iterator.next();
									JSONObject listInfo = TypeUtils.getJsonObject(datas, key);
									nanner.setImage(TypeUtils.getJsonString(listInfo, "Image", ""));
									nanner.setId(TypeUtils.getJsonString(listInfo, "id", ""));
									nanner.setTitle(TypeUtils.getJsonString(listInfo, "Title", ""));
									nanner.setURL(TypeUtils.getJsonString(listInfo, "URL", ""));
									localImages.add(nanner);

								}
								setBanner();
								LogUtils.println("zhangyiyionSuccessBANNER------" + response.body());

							}

							@Override
							public void onError(Response<String> response) {
								LogUtils.println("zhangyiyionErrorBANNER------" + response.body());
							}
						}


				);

	}

	public static int getResId(String variableName, Class<?> c) {
		try {
			Field idField = c.getDeclaredField(variableName);
			return idField.getInt(idField);
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
	}

	@Override
	public void onRefresh() {
		ToastUtil.showShortToast("刷新数据");
		mSwipeRefreshLayout.setRefreshing(false);
	}

	public void showMyToast() {
		MyStylesToast myStylesToast = new MyStylesToast(getActivity(), R.layout.mytoast_layout, "敬请期待");
		myStylesToast.show(1000);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.homemore1:
				showMyToast();
				break;
			case R.id.homemore2:
				showMyToast();
				break;
			case R.id.homemore3:
				showMyToast();
				break;
			case R.id.homemore4:
				showMyToast();
				break;
			case R.id.homemore5:
				showMyToast();
				break;
			case R.id.homemore6:
				showMyToast();
				break;
			case R.id.homemore7:
				showMyToast();
				break;
			case R.id.homemore8:
				showMyToast();
				break;
		}

	}

	@Override
	public void GoMoney(String id) {
		ToastUtil.showShortToast("点击了");
		initProducturlGo(id);
	}


	protected class MyScrollListener implements AbsListView.OnScrollListener {

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
							 int visibleItemCount, int totalItemCount) {
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if (SCROLL_STATE_TOUCH_SCROLL == scrollState) {
				View currentFocus = getActivity().getCurrentFocus();
				if (currentFocus != null) {
					currentFocus.clearFocus();
				}
			}
		}

	}

	@Override
	public void onItemClick(int position) {
		Intent intent = new Intent(getActivity(), MyWebActivity.class);
//		intent.putExtra("type", "recharge");
		intent.putExtra("title", localImages.get(position).getTitle());
		intent.putExtra("url", localImages.get(position).getURL());
		startActivity(intent);

//		Intent intent = new_icon Intent(getActivity(), BindingCardActivity.class);
//		intent.putExtra("type", "recharge");
//		startActivity(intent);

	}

	public class LocalImageHolderView implements Holder<BannerInfo> {
		private ImageView imageView;

		@Override
		public View createView(Context context) {
			imageView = new ImageView(context);
			imageView.setScaleType(ImageView.ScaleType.FIT_XY);
			return imageView;
		}

		@Override
		public void UpdateUI(Context context, final int position, BannerInfo bannerInfo) {
			GlideUtil.loadImageFitXY(context, bannerInfo.getImage(), imageView);
//			imageView.setImageResource(data);
		}
	}


	private void setBanner() {
		if (localImages.size() <= 0) {
			convenient.setVisibility(View.GONE);
			return;
		}

		for (int position = 0; position < 3; position++) {

		}
		//自定义你的Holder，实现更多复杂的界面，不一定是图片翻页，其他任何控件翻页亦可。
		convenient.setPages(
				new CBViewHolderCreator<LocalImageHolderView>() {
					@Override
					public HomeTabFragment.LocalImageHolderView createHolder() {
						return new HomeTabFragment.LocalImageHolderView();
					}
				}, localImages)
				//设置指示器是否可见
				.setPointViewVisible(true)
				//设置自动切换（同时设置了切换时间间隔）
				.startTurning(5000)
				//设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
				.setPageIndicator(new int[]{R.mipmap.no, R.mipmap.off})
				//设置指示器的方向（左、中、右）
				.setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
				//设置点击监听
				.setOnItemClickListener(HomeTabFragment.this)
				//设置手动影响（设置了该项无法手动切换）
				.setManualPageable(true);
	}
}